import editForm from "../form.vue";
import { message } from "@/utils/message";
import {
  queryProduceTaskByAll,
  checkUserAndPaperStatus
} from "@/api/produceexam";
import { addDialog } from "@/components/ReDialog";
import { type FormItemProps } from "../utils/types";
import { type PaginationProps } from "@pureadmin/table";
import { reactive, ref, onMounted, onBeforeUnmount, h } from "vue";
import { useNav } from "@/layout/hooks/useNav";
import { ElMessageBox } from "element-plus";
import { emitter } from "@/utils/mitt";

export function useRole() {
  const { updateStudentInto } = useNav();

  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "考试名称",
      prop: "name",
      minWidth: 140
    },
    {
      label: "开始考试时间",
      prop: "starttime",
      minWidth: 130
    },
    {
      label: "禁止入场时间",
      prop: "endtime",
      minWidth: 130
    },
    {
      label: "考试试卷",
      prop: "paperName",
      minWidth: 140
    },
    {
      label: "考试时长",
      prop: "paperTimes",
      minWidth: 80,
      formatter: row => {
        return `${row.paperTimes}(分钟)`;
      }
    },
    {
      label: "试卷总分数",
      prop: "paperScore",
      minWidth: 80,
      formatter: row => {
        return `${row.paperScore}分`;
      }
    },
    {
      label: "操作",
      fixed: "right",
      width: 150,
      slot: "operation"
    }
  ];

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  async function onSearch() {
    loading.value = true;
    queryProduceTaskByAll({
      pageSize: pagination.pageSize,
      currentPage: pagination.currentPage
    })
      .then(res => {
        if (res.success) {
          dataList.value = res.data.list;
          pagination.total = res.data.total;
          loading.value = false;
        } else {
          message("查询数据异常:" + res.errMsg, { type: "error" });
        }
      })
      .catch(error => {
        message("查询数据异常:" + JSON.stringify(error), { type: "error" });
      });
  }

  async function checkUserStatus(row?: FormItemProps) {
    checkUserAndPaperStatus({
      taskId: row?.id
    })
      .then(res => {
        if (res.success) {
          row.taskZt = res.data;
          if (res.data == 1) {
            message("考试任务异常", { type: "error" });
          } else if (res.data == 2) {
            message("考试任务已经过期", { type: "error" });
          } else if (res.data == 3) {
            message("考试任务还没生效", { type: "error" });
          } else if (res.data == 4) {
            message("请先完善个人信息", { type: "error" });
            updateStudentInto(); //进入个人信息修界面
          } else if (res.data == 5) {
            ElMessageBox.confirm(
              "已经存在未结束的考试记录，是否要重新开始考试？",
              "系统提示",
              {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
                dangerouslyUseHTMLString: true,
                draggable: true
              }
            )
              .then(() => {
                openDialog("参加考试", row); //进入正式考试页面
              })
              .catch(() => {
                console.log("取消?");
              });
          } else if (res.data == 6) {
            message("您已考试结束", { type: "error" });
          } else if (res.data == 7) {
            message("正在考试中", { type: "error" });
          } else if (res.data == 0) {
            openDialog("参加考试", row); //进入正式考试页面
          }
        } else {
          message("查询数据异常:" + res.errMsg, { type: "error" });
        }
      })
      .catch(error => {
        message("查询数据异常:" + JSON.stringify(error), { type: "error" });
      });
  }
  function openDialog(title = "参加考试", row?: FormItemProps) {
    addDialog({
      title: `${title}`,
      props: {
        formInline: {
          id: row?.id ?? "",
          name: row?.name ?? "",
          paperid: row?.paperid ?? "",
          paperName: row?.paperName ?? "",
          starttime: row?.starttime ?? "",
          endtime: row?.endtime ?? "",
          description: row?.description ?? "",
          taskZt: row?.taskZt ?? 1,
          paperTimes: row?.paperTimes ?? 0,
          paperScore: row?.paperScore ?? 0
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: true,
      showClose: false,
      closeOnClickModal: false,
      closeOnPressEscape: false,
      headerRenderer: ({ titleId, titleClass }) => (
        // jsx 语法
        <div class="flex flex-row justify-between">
          <h4 id={titleId} class={titleClass}>
            试卷名称：{row.paperName}
          </h4>
          <h4 id={titleId} class={titleClass}>
            考试时长：{row.paperTimes} (分钟)
          </h4>
          <h4 id={titleId} class={titleClass}>
            试卷分数：{row.paperScore} (分)
          </h4>
        </div>
      ),
      hideFooter: true,
      contentRenderer: () => h(editForm, { ref: formRef })
    });
  }

  onMounted(() => {
    onSearch();
    emitter.on("onSearchEmit", () => {
      onSearch();
    });
  });

  onBeforeUnmount(() => {
    // 解绑`openPanel`公共事件，防止多次触发
    emitter.off("onSearchEmit");
  });

  return {
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    checkUserStatus,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
